import 'package:flutter/material.dart';
import '../utils/adapt.dart';
import '../utils/request.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:provider/provider.dart';
import '../event_bus.dart';

class List extends StatefulWidget {
  List({Key? key}) : super(key: key);

  @override
  _ListState createState() => _ListState();
}

class _ListState extends State<List> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  ScrollController _scrollController = ScrollController();
  int _currentIndex = 1;
  var _list1 = [];
  var _list2 = [];
  var _list3 = [];
  var _list4 = [];
  bool _hasMore1 = true;
  bool _hasMore3 = true;
  void _getAll() async {
    // 全部mv
    // if (_list1.length != 0) return;
    if (!_hasMore1) return;
    EasyLoading.show(status: 'loading...');
    var res = await getHttp('/mv/all?limit=100&offset=1');
    EasyLoading.dismiss();
    this.setState(() {
      _list1 = res['data'];
      _hasMore1 = res['hasMore'];
    });
    print("length:${res['hasMore']}");
    // _getNEW();
  }

  void _getNEW() async {
    if (_list2.length != 0) return;
    // 最新mv
    // EasyLoading.show(status: 'loading...');
    var res = await getHttp('/mv/first?limit=100');
    // EasyLoading.dismiss();
    this.setState(() {
      _list2 = res['data'];
    });
    _getWY(1);
  }

  void _getWY(offset) async {
    if (!_hasMore3) return;
    // 网易mv
    // EasyLoading.show(status: 'loading...');
    var res = await getHttp('/mv/exclusive/rcmd?limit=100&offset=$offset');
    // EasyLoading.dismiss();
    this.setState(() {
      _list3 = res['data'];
      _hasMore3 = res['more'];
    });
    _getRecommend();
  }

  void _getRecommend() async {
    // 获取推荐mv
    // EasyLoading.show(status: 'loading...');
    var res = await getHttp('/personalized/mv');
    // EasyLoading.dismiss();
    this.setState(() {
      _list4 = res['result'];
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 40) {}
    });
    super.initState();
    _tabController = TabController(
      initialIndex: 1,
      length: 4,
      vsync: this,
    );

    _getAll();
    _getNEW();
  }

  @override
  Widget build(BuildContext context) {
    return NestedScrollView(
      controller: _scrollController,
      headerSliverBuilder: (BuildContext context, bool b) {
        return [
          SliverAppBar(
            pinned: true,
            floating: true,
            expandedHeight: Adapt.px(20),
            flexibleSpace: FlexibleSpaceBar(),
            bottom: TabBar(
              indicatorColor: Colors.red,
              labelColor: Colors.red,
              unselectedLabelColor: Colors.white60,
              labelPadding: const EdgeInsets.only(
                bottom: 12,
              ),
              controller: _tabController,
              isScrollable: false,
              onTap: (index) {
                this.setState(() {
                  _currentIndex = index;
                });
              },
              tabs: [
                Text(
                  "全部MV",
                  style: TextStyle(
                    fontSize: Adapt.px(26),
                  ),
                ),
                Text(
                  "最新MV",
                  style: TextStyle(
                    fontSize: Adapt.px(26),
                  ),
                ),
                Text(
                  "网易出品MV",
                  style: TextStyle(
                    fontSize: Adapt.px(26),
                  ),
                ),
                Text(
                  "推荐MV",
                  style: TextStyle(
                    fontSize: Adapt.px(26),
                  ),
                ),
              ],
            ),
          ),
        ];
      },
      body: TabBarView(
        controller: _tabController,
        children: [
          TabbarPage(_list1),
          _list2.length == 0 ? Text("") : TabbarPage(_list2),
          TabbarPage(_list3),
          TabbarPage(_list4),
        ],
      ),
    );
  }
}

class TabbarPage extends StatefulWidget {
  var _list;
  TabbarPage(this._list, {Key? key}) : super(key: key);

  @override
  _TabbarPageState createState() => _TabbarPageState(this._list);
}

class _TabbarPageState extends State<TabbarPage>
    with AutomaticKeepAliveClientMixin {
  var _list;
  _TabbarPageState(this._list);
  @override
  Widget build(BuildContext context) {
    // super.build(context);
    return _list.length == 0
        ? Center(
            child: Text(
              "数据加载中...",
              style: TextStyle(
                fontSize: Adapt.px(26),
              ),
            ),
          )
        : GridView.builder(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              mainAxisSpacing: 2,
              crossAxisSpacing: 2,
              crossAxisCount: 2,
              childAspectRatio: 5 / 4.2,
            ),
            itemCount: _list.length,
            padding: EdgeInsets.symmetric(
                horizontal: Adapt.px(10), vertical: Adapt.px(20)),
            itemBuilder: (BuildContext context, int index) {
              return Container(
                color: Colors.grey[200],
                child: InkWell(
                  onTap: () {
                    var _ids = _list.map((item) {
                      return item['id'];
                    }).toList();
                    eventbus.fire(new changeAudioState(false)); // 暂停音乐
                    Navigator.pushNamed(context, "/videoswiper2",
                        arguments: {"currentIndex": index, "ids": _ids});
                  },
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      AspectRatio(
                        aspectRatio: 3 / 1.7,
                        child: Image.network(
                          _list[index]['cover'] != null
                              ? _list[index]['cover']
                              : _list[index]['picUrl'] + "?param=190y127",
                        ),
                      ),
                      Text(
                        "${_list[index]['name']}",
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: Adapt.px(26),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
